package com.jg.visitor.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Slf4j
public class ContextHolderUtils {

	private static final Map<String, HttpSession> sessionMap = new HashMap<>();

	/**
	 * SpringMvc下获取request
	 */
	
	public static HttpServletResponse getResponse() {
		return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();

	}


	/**
	 * SpringMvc下获取session
	 */
	public static HttpSession getSession() {
		HttpServletRequest request = getRequest();

		return request.getSession();
	}

	public static HttpServletRequest getRequest() {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();

		assert requestAttributes != null;

		return requestAttributes.getRequest();

	}

	public static HttpSession getSession(String sessionId){
		HttpSession session = sessionMap.get(sessionId);
		return session == null ? getSession() : session;
	}
	
	public static void removeSession(String sessionId){
		sessionMap.remove(sessionId);
	}


	public static   String getRemoteIP() {
		HttpServletRequest request   = getRequest();
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		}
		return request.getHeader("x-forwarded-for");
	}

}
